package gomail

import (
	"crypto/tls"
	"hg/config"
	"hg/models"
	"hg/pkg/database"
	"math/rand"
	"strconv"
	"time"

	"github.com/sirupsen/logrus"
	"gopkg.in/gomail.v2"
)

func EmailCodeToUser(user *models.Userinfo) {
	config := config.GetConfig()
	d := gomail.NewDialer(config.EmialHost, config.EmialPort, config.EmialUserName, config.EmialPassword)
	m := gomail.NewMessage()
	m.SetHeader("From", config.EmialUserName)
	m.SetHeader("To", user.Email)  // 收件人地址
	m.SetHeader("Subject", "验证码") // 设置主题
	code := getVerificationCode()
	data := &models.EmailCodes{
		Username: user.Username,
		Code:   code,
		Expiry: time.Now().Add(300 * time.Second),
	}
	err := database.InsertCodeToDB(data)
	if err!=nil{
		logrus.Println(err)
	}
	m.SetBody("text/plain", "【沙漏视频】验证码"+strconv.Itoa(code)+"用于沙漏视频身份验证，5分钟内有效，请勿泄露和转发。如非本人操作，请忽略此短信。") // 设置邮件正文
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

func getVerificationCode() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
    code := r.Intn(900000) + 100000
	return code
}


// if err := c.ShouldBindJSON(&user); err != nil {
// 	c.JSON(400, gin.H{"error": err.Error()})
// 	return
// }
